package com.dylan_wang.capturescreen;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.black.copyfloatingwindow.AppConnect;

import java.text.SimpleDateFormat;

public class MainActivity extends Activity {

    private SharedPreferences        shSetting;
    private SharedPreferences.Editor editorSetting;
    private String                   tag      = "悬浮时间MainActivity";
    private int                      colorRed = 125, colorGreen = 125, colorBlue = 125;// 初始化数值 十六进制
    private TextView               testTV;// 演示时间文本
    private TextView               textVtimeCorrect;
    private WebView                mainweb;
    private EditText               ipEditext;
    private Button                 mButtonSave;
    private int                    result                   = 0;
    private Intent                 intent                   = null;
    private int                    REQUEST_MEDIA_PROJECTION = 1;
    private MediaProjectionManager mMediaProjectionManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Window window = this.getWindow();
        // 去标题栏
        window.requestFeature(window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        mMediaProjectionManager = (MediaProjectionManager) getApplication().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        // 获取本地存储对象
        shSetting = getSharedPreferences("setting", MODE_PRIVATE);
        editorSetting = shSetting.edit();

        // 获取所有View对象
        testTV = (TextView) findViewById(R.id.testTV);// 演示时间文本
        SeekBar seekBarRed = (SeekBar) findViewById(R.id.seekBarRed);// 红色推动条
        SeekBar seekBarGreen = (SeekBar) findViewById(R.id.seekbarGreen);// 绿色推动条
        SeekBar seekBarBlue = (SeekBar) findViewById(R.id.seekbarBlue);// 蓝色推动条
        SeekBar seekBarTextSize = (SeekBar) findViewById(R.id.seekBarTextSize);// 大小拖动条
        SeekBar seekBarTimeCorrect = (SeekBar) findViewById(R.id.seekBarTimeCorrect);// 时间矫正拖动条
        textVtimeCorrect = (TextView) findViewById(R.id.textVtimeCorrect);
        TextView showText = (TextView) findViewById(R.id.textView1);// 在线文本

        ipEditext = findViewById(R.id.ipsaveedi);
        mButtonSave = findViewById(R.id.saveButton);
        ipEditext.setText(shSetting.getString("ipadr", "gyyjjikl.cn:12304"));

        mButtonSave.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ipEditext.getText().toString().equals("")) {
                    Toast.makeText(getApplicationContext(), "请输入正确的服务器地址!", Toast.LENGTH_SHORT).show();
                    return;
                }

                editorSetting.putString("ipadr", ipEditext.getText().toString()).commit();
                Toast.makeText(getApplicationContext(), "已保存地址!", Toast.LENGTH_SHORT).show();

            }
        });

        // 读取本地存储的值 设置各种拖动条的值
        seekBarRed.setProgress(shSetting.getInt("colorRed", 125));// 红色拖动条
        seekBarGreen.setProgress(shSetting.getInt("colorGreen", 125));// 绿色拖动条
        seekBarBlue.setProgress(shSetting.getInt("colorBlue", 125));// 蓝色拖动条
        seekBarTextSize.setProgress(shSetting.getInt("textSize", 40));// 文字大小拖动条
        seekBarTimeCorrect.setProgress(shSetting.getInt("timeCorrect", 0) + 5);// 时间矫正拖动条

        // 设置时间矫正的值 设置给文本提示
        textVtimeCorrect.setText("时间矫正(" + shSetting.getInt("timeCorrect", 0) + ")");
        // 给演示文本一个当前时间文本
        SimpleDateFormat s = new SimpleDateFormat("HH:mm:ss");
        testTV.setText("" + s.format(new java.util.Date()));

        // 给color赋初始值
        colorRed = shSetting.getInt("colorRed", 125);
        colorGreen = shSetting.getInt("colorGreen", 125);
        colorBlue = shSetting.getInt("colorBlue", 125);
        // 设置测试文本的值和颜色
        testTV.setTextColor(Color.parseColor("#" + Integer.toHexString(shSetting.getInt("colorRed", 125)) + ""
                + Integer.toHexString(shSetting.getInt("colorGreen", 125)) + ""
                + Integer.toHexString(shSetting.getInt("colorBlue", 125))));
        // /设置大小
        testTV.setTextSize(shSetting.getInt("textSize", 40));

        // 在线配置数据

        String onlinetext = AppConnect.getInstance(this).getConfig("showText3", "请拖动Drag选择颜色O(∩_∩)O~");
        showText.setText(onlinetext);
        Log.d("-->", "悬浮时间是第一次启动" + onlinetext);

        /** 网赚入口Button ***********************************************************/
        // 获取在线数据是否显示button
        String onlineBnGone = AppConnect.getInstance(this).getConfig("linknewpagebn2", "0");

        Button linknewpageBn = (Button) findViewById(R.id.linknewpageBn);// 获取Button的对象
        Button tuijainbn = (Button) findViewById(R.id.tuijainbn);


        //        if (onlineBnGone.equals("0")) {
        linknewpageBn.setVisibility(View.GONE);// 隐藏
        tuijainbn.setText("推荐");
        Log.e(tag, "在这里隐藏了Button");
        //        } else {
        //            linknewpageBn.setVisibility(View.VISIBLE);// 显示按钮
        //            tuijainbn.setText("赚赚");
        //            Log.e(tag, "在这里显示了Button");
        //        }

        linknewpageBn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent in = new Intent(MainActivity.this, Newpage.class);
                startActivity(in);
                /**
                 * 2.1 获取用户虚拟货币 步骤 1: 从服务器端获取用户点数/虚拟货币余额:
                 * AppConnect.getInstance(this).getPoints(this); 步骤 2: 确保在 this
                 * 类中实现 UpdatePointsListener 接口，实现下面癿两个回调方法，用亍异步接 收服务器返回癿结果:
                 * public void getUpdatePoints(String currencyName,
                 * intpointTotal);//获取成功 public void
                 * getUpdatePointsFailed(String error);//获取失败
                 *
                 * 2.2 花费用户虚拟货币
                 * AppConnect.getInstance(this).spendPoints(intamount,this);
                 * 调用此方法癿响应结果将通过this中实现癿 UpdatePointsListener接口返回 2.3 奖励用户虚拟货币
                 * AppConnect.getInstance(this).awardPoints(intamount,this);
                 * 调用此方法癿响应结果将通过this中实现癿 UpdatePointsListener接口返回
                 * 注意：所有通过万普广告获得癿虚拟货币将自劢给予到用户，无需调用该接口。该接口仅用亍用户
                 * 完成了开发者指定癿其他任务癿情况下额外给予用户虚拟货币。
                 *
                 */

            }
        });

        /** 这里webview ******************************************************/
        mainweb = (WebView) findViewById(R.id.mainweb);
        // 这个方法保证网页在webview中打开
        mainweb.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                Log.d(tag, "这里是loadURL方法里面");
                return true;
            }
        });
        mainweb.loadUrl("http://v-zuan.com:8080/myapp/mainweb.jsp");
        // mainweb.loadUrl("http://faming3890.6655.la/ZZZfloatdynamic/mainweb.jsp");//
        // 测试
        // 获取webview的设置对象
        WebSettings websetting = mainweb.getSettings();
        // 设置js可以直接打开窗口，如window.open()，默认为false
        websetting.setJavaScriptCanOpenWindowsAutomatically(true);
        // 是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        websetting.setJavaScriptEnabled(true);
        // 设置支持js的调用
        Mainwebobj mwo = new Mainwebobj(MainActivity.this);
        // 暴露安卓接口
        mainweb.addJavascriptInterface(mwo, "mainweb");
        // Log.d(tag, "这是loadURL方法执行之后");

        // 红色拖动条
        seekBarRed.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            public void onStopTrackingTouch(SeekBar s) {
                Log.e(tag, "结束对seekBar的拖动,现在 seekBar的值是:" + s.getProgress());
                // 拖动结束后吧拖动条的值写入本地存储
                editorSetting.putInt("colorRed", colorRed).commit();

                Toast.makeText(getApplicationContext(), "已保存O(∩_∩)O！", Toast.LENGTH_LONG).show();
                // 启动显示秒的悬浮窗
                Intent intentSecond = new Intent(getApplicationContext(), FxService.class);
                if (intentSecond != null) {
                    Log.e(tag, "如果显示秒的不等于null则关闭的方法已经执行!");
                    stopService(intentSecond);
                }
                startService(intentSecond);// 注意是startService
            }

            public void onStartTrackingTouch(SeekBar s) {
                Log.e(tag, "开始对seekBar的拖动,现在 seekBar的值是:" + s.getProgress());

            }

            public void onProgressChanged(SeekBar arg0, int num, boolean arg2) {
                // 只有值是这个范围才能保证十六进制是两位数
                if (num >= 16 && num <= 255) {
                    colorRed = num;// num值赋值全局变量
                    Log.e(tag, "红色seekbar的值:" + num + "十六进制的值是:" + Integer.toHexString(colorRed));

                    testTV.setTextColor(Color.parseColor("#" + Integer.toHexString(colorRed) + ""
                            + Integer.toHexString(colorGreen) + "" + Integer.toHexString(colorBlue)));
                }
            }
        });
        // 绿色拖动条
        seekBarGreen.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            public void onStopTrackingTouch(SeekBar arg0) {
                // 拖动结束后吧拖动条的值写入本地存储
                editorSetting.putInt("colorGreen", colorGreen).commit();

                Toast.makeText(getApplicationContext(), "已保存O(∩_∩)O！", Toast.LENGTH_LONG).show();
                // 启动显示秒的悬浮窗
                Intent intentSecond = new Intent(getApplicationContext(), FxService.class);
                if (intentSecond != null) {
                    Log.e(tag, "如果显示秒的不等于null则关闭的方法已经执行!");
                    stopService(intentSecond);
                }
                startService(intentSecond);// 注意是startService
            }

            public void onStartTrackingTouch(SeekBar arg0) {
            }

            public void onProgressChanged(SeekBar arg0, int num, boolean arg2) {
                // 只有值是这个范围才能保证十六进制是两位数
                if (num >= 16 && num <= 255) {
                    Log.e(tag, "绿色seekbar的值" + num);
                    colorGreen = num;// num值赋值全局变量

                    testTV.setTextColor(Color.parseColor("#" + Integer.toHexString(colorRed) + ""
                            + Integer.toHexString(colorGreen) + "" + Integer.toHexString(colorBlue)));

                }
            }
        });
        // 蓝色拖动条
        seekBarBlue.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            public void onStopTrackingTouch(SeekBar arg0) {
                // 拖动结束后吧拖动条的值写入本地存储
                editorSetting.putInt("colorBlue", colorBlue).commit();

                Toast.makeText(getApplicationContext(), "已保存O(∩_∩)O！", Toast.LENGTH_LONG).show();
                // 启动显示秒的悬浮窗
                Intent intentSecond = new Intent(getApplicationContext(), FxService.class);
                if (intentSecond != null) {
                    Log.e(tag, "如果显示秒的不等于null则关闭的方法已经执行!");
                    stopService(intentSecond);
                }
                startService(intentSecond);// 注意是startService
            }

            public void onStartTrackingTouch(SeekBar arg0) {
            }

            public void onProgressChanged(SeekBar arg0, int num, boolean arg2) {
                // 只有值是这个范围才能保证十六进制是两位数
                if (num >= 16 && num <= 255) {
                    Log.e(tag, "蓝色seekbar的值" + num);
                    colorBlue = num;// num值赋值全局变量

                    testTV.setTextColor(Color.parseColor("#" + Integer.toHexString(colorRed) + ""
                            + Integer.toHexString(colorGreen) + "" + Integer.toHexString(colorBlue)));

                }
            }
        });
        // 悬浮窗大小拖动条
        seekBarTextSize.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seek) {
                // TODO Auto-generated method stub
                // 拖动结束后吧拖动条的值写入本地存储
                editorSetting.putInt("textSize", seek.getProgress()).commit();
                Toast.makeText(getApplicationContext(), "已保存O(∩_∩)O！", Toast.LENGTH_LONG).show();
                // 启动显示秒的悬浮窗
                Intent intentSecond = new Intent(getApplicationContext(), FxService.class);
                if (intentSecond != null) {
                    Log.e(tag, "如果显示秒的不等于null则关闭的方法已经执行!");
                    stopService(intentSecond);
                }
                startService(intentSecond);// 注意是startService

            }

            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgressChanged(SeekBar arg0, int num, boolean arg2) {
                // TODO Auto-generated method stub
                Log.e(tag, "大小拖动条设置文本大小,拖动条值是:" + num);
                testTV.setTextSize(num);

            }
        });
        // 时间矫正拖动条
        seekBarTimeCorrect.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar arg0) {
                // TODO Auto-generated method stub
                // Toast.makeText(getApplicationContext(),
                // "该功能正在开发哦O(∩_∩)O!请期待下个版本更新吧!", 1).show();
                SimpleDateFormat s = new SimpleDateFormat("HH:mm:ss");
                testTV.setText("" + s.format(new java.util.Date()));
                // 启动显示秒的悬浮窗
                Intent intentSecond = new Intent(getApplicationContext(), FxService.class);
                if (intentSecond != null) {
                    Log.e(tag, "如果显示秒的不等于null则关闭的方法已经执行!");
                    stopService(intentSecond);
                }
                startService(intentSecond);// 注意是startService

            }

            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgressChanged(SeekBar arg0, int num, boolean arg2) {
                // TODO Auto-generated method stub
                Log.e(tag, "时间矫正拖动条传来的值是:" + num);// 修改进度条的同时 注意 要修改界面UI的值
                if (num >= 0 && num <= 50) {
                    num = num - 25;
                    Log.e(tag, "矫正值是:" + num);
                    // 写入本地存储
                    editorSetting.putInt("timeCorrect", num).commit();
                    textVtimeCorrect.setText("时间矫正(" + num + ")");
                    testTV.setText("矫正时间:  " + num + "秒");

                }

            }
        });

        Switch switchButton = (Switch) findViewById(R.id.switch1);
        switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {


                LogPlus.e("------> 开关状态" + isChecked);
                if (isChecked) {
                    startIntent();
                } else {
                    //关闭按钮
                }


            }
        });

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void startIntent() {
        if (intent != null && result != 0) {
            Log.i(tag, "user agree the application to capture screen");
            //Service1.mResultCode = resultCode;
            //Service1.mResultData = data;
            ((ShotApplication) getApplication()).setResult(result);
            ((ShotApplication) getApplication()).setIntent(intent);
            //Intent intent = new Intent(getApplicationContext(), Service1.class);
            //startService(intent);
            //Log.i(TAG, "start service Service1");
        } else {
            startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
            //Service1.mMediaProjectionManager1 = mMediaProjectionManager;
            ((ShotApplication) getApplication()).setMediaProjectionManager(mMediaProjectionManager);
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_MEDIA_PROJECTION) {
            if (resultCode != Activity.RESULT_OK) {
                return;
            } else if (data != null && resultCode != 0) {
                Log.i(tag, "user agree the application to capture screen");
                //Service1.mResultCode = resultCode;
                //Service1.mResultData = data;
                result = resultCode;
                intent = data;
                ((ShotApplication) getApplication()).setResult(resultCode);
                ((ShotApplication) getApplication()).setIntent(data);
                Intent intent = new Intent(getApplicationContext(), Service1.class);
                startService(intent);
                Log.i(tag, "start service Service1");

                MainActivity.this.finish();
            }
        }
    }

    // 移除
    public void bn6(View v) {
        // 移除所有悬浮窗
        /*
         * intent = new Intent(MainActivity.this, FxService.class);
         * stopService(intent); intentSecond = new Intent(MainActivity.this,
         * FServiceSecond.class); stopService(intentSecond);
         */
    }

    // 强制关闭
    public void bn4(View v) {
        // Toast.makeText(this, "强制关闭！", 1).show();


        // 自杀
        int pid = android.os.Process.myPid();// 获取自己的pid
        android.os.Process.killProcess(pid);// 通过pid自杀

    }

    // 显示秒悬浮窗
    public void bn7(View v) {
    }

    // 积分墙
    public void bn1(View v) {
        Toast.makeText(this, "非常感谢您的支持！", Toast.LENGTH_LONG).show();
        // 积分墙
        // AppConnect.getInstance(this).showOffers(this);
        // setContentView(R.layout.start_layout);
        // 跳转到start页面
        Intent in = new Intent();
        in.setClass(getApplicationContext(), StartLayout.class);
        startActivity(in);

        this.finish();

    }

    // 展示有米的积分墙
    public void tuijianbn(View v) {

    }

    // 反馈建议
    public void bn2(View v) {
        // 把群号复制到手机剪贴板
        ClipboardManager clipboardManager2 = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipboardManager2.setPrimaryClip(ClipData.newPlainText(null, "374344451"));
        if (clipboardManager2.hasPrimaryClip()) {
            clipboardManager2.getPrimaryClip().getItemAt(0).getText();
        }
        Toast.makeText(this, "感谢您的支持！\nQQ群号已复制", Toast.LENGTH_LONG).show();
        // 调用反馈建议接口
        AppConnect.getInstance(this).showFeedback(this);

    }

    // 检查升级
    public void bn3(View v) {
        Toast.makeText(this, "正在获取版本信息~~~", Toast.LENGTH_LONG).show();
        Toast.makeText(this, "有新版会提示您哦~", Toast.LENGTH_LONG).show();
        // 调用检查升级接口
        AppConnect.getInstance(this).checkUpdate(this);

    }

    @Override
    protected void onDestroy() {
        // TODO 自动生成的方法存根
        super.onDestroy();
        // 调用万普的结束接口
        AppConnect.getInstance(this).close();
    }

    public void onResume() {
        super.onResume();

    }

    public void onPause() {
        super.onPause();

    }
}
